/**
 * @module VcMeasurement
 * @file VcMeasurement.ts
 */
class VcMeasurementCore {
  private static instance: VcMeasurementCore;

  private map: Cesium.Viewer | null = null; // 定义地图属性

  private measurementsRef: any | null = null; // 绘画结束监听

  private constructor() {
    // 私有构造函数，防止实例化
  }

  /**
   * 返回VcMeasurementCore类的实例。
   * @returns VcMeasurementCore实例。
   */
  public static getInstance(): VcMeasurementCore {
    if (!VcMeasurementCore.instance) {
      VcMeasurementCore.instance = new VcMeasurementCore();
    }
    return VcMeasurementCore.instance;
  }

  /**
   * 设置VcDrawCore实例的地图。
   * @param map - Cesium 地图对象。
   */
  public setMap(map: Cesium.Viewer, measurementsRef: any) {
    this.map = map;
    this.measurementsRef = measurementsRef;
  }

  /**
   * 距离
   */
  public openDistanceTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('distance');
  }

  /**
   * 三角距离
   */
  public openComponentDistanceTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('component-distance');
  }

  /**
   * 折线距离
   */
  public openPolylineTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('polyline');
  }

  /**
   * 水平距离
   */
  public openHorizontalTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('horizontal');
  }

  /**
   * 垂直距离
   */
  public openVerticalTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('vertical');
  }

  /**
   * 地表高度
   */
  public openHeightTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('height');
  }

  /**
   * 面积
   */
  public openAreaTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('area');
  }

  /**
   * 坐标
   */
  public openPointTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('point');
  }

  /**
   * 矩形
   */
  public openRectangleTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('rectangle');
  }

  /**
   * 矩形
   */
  public openRegularTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('regular');
  }

  /**
   * 圆
   */
  public openCircleTool() {
    if (this.map == null) {
      return;
    }
    this.toggleAction('circle');
  }

  public closeAllMeasurement() {
    if (this.map == null) {
      return;
    }
    try {
      this.measurementsRef.clearAll();
    } catch (e) {
      console.log('clearAll error', e);
    }
  }

  /**
   * 执行测量操作
   * @param name  'distance' | 'area' | 'height' | 'angle' | 'point' | 'clear' | 'rectangle' | 'regular' | 'circle'
   */
  public toggleAction(name: string) {
    try {
      this.measurementsRef.toggleAction(name);
    } catch (e) {
      console.log('toggleAction error', e);
    }
  }
}

export const VcMeasurement = {
  core: VcMeasurementCore.getInstance(),
};
